import {PlusOutlined, TableOutlined, EyeOutlined, DeleteOutlined} from '@ant-design/icons';
import {PageContainer} from '@ant-design/pro-components';
import {useRequest, history} from '@umijs/max';
import {Button, Card, Input, List, Modal, Pagination, Tooltip, Typography} from 'antd';
import type {CardListItemDataType} from './data.d';
import {delForm, queryListForm} from './service';
import useStyles from './style.style';
import {useCallback, useState} from 'react';
import {debounce} from "@/utils/debounce";
import dayjs from "dayjs";

const {Paragraph} = Typography;
const CardList = () => {
  const {styles} = useStyles();
  const [searchText, setSearchText] = useState<string>();
  const [pageInfo, setPageInfo] = useState({page: 1, size: 11})
  const {data, loading, refresh} = useRequest(() => {
    return queryListForm({
      page: pageInfo.page,
      size: pageInfo.size,
      keyWords: searchText
    });
  }, {refreshDeps: [pageInfo]});
  const list = data?.current_data || [];

  const handleDel: any = useCallback(debounce((item: any) => {
    Modal.confirm({
      title: `删除表格`,
      content: <div>
        确定删除 <b>{item.name}</b> 表格吗？
        <p style={{color: 'red'}}>删除后不可恢复，请谨慎操作！</p>
      </div>,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await delForm({
          id: item.id
        })
        setPageInfo({
          ...pageInfo,
          page: 1,
        })
        return true
      },
    });
  }), [])

  const content = (
    <div className={styles.pageHeaderContent}>
      <p>
        <span style={{color: 'red'}}>请培训后或在导师指导下操作！</span>用于展示设计过的表格列表，支持查看、编辑等场景。
      </p>
      <div className={styles.contentLink}>
        <Input.Search
          placeholder="请输入"
          enterButton="搜索"
          value={searchText}
          onChange={(e) => {
            setSearchText(e.target.value);
          }}
          onSearch={ ()=> {
            refresh()
          }}
          style={{maxWidth: 522, width: '100%'}}
        />
        {/*<Button type="primary" onClick={() => {*/}
        {/*  history.push(`/dynamic-form/design-form`);*/}
        {/*}}>*/}
        {/*  <PlusOutlined/> 新增表格*/}
        {/*</Button>*/}
        {/*<a>*/}
        {/*  <img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/MjEImQtenlyueSmVEfUD.svg"/>{' '}*/}
        {/*  快速开始*/}
        {/*</a>*/}
        {/*<a>*/}
        {/*  <img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/NbuDUAuBlIApFuDvWiND.svg"/>{' '}*/}
        {/*  产品简介*/}
        {/*</a>*/}
        {/*<a>*/}
        {/*  <img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/ohOEPSYdDTNnyMbGuyLb.svg"/>{' '}*/}
        {/*  产品文档*/}
        {/*</a>*/}
      </div>
    </div>
  );

  return (
    <PageContainer content={content}
      // extraContent={extraContent}
    >
      <div className={styles.cardList}>
        <List<Partial<CardListItemDataType>>
          rowKey="id"
          loading={loading}
          grid={{
            gutter: 16,
            xs: 1,
            sm: 2,
            md: 3,
            lg: 3,
            xl: 4,
            xxl: 4,
          }}
          dataSource={[{}, ...list]}
          renderItem={(item) => {
            if (item && item.id) {
              return (
                <List.Item
                  key={item.id}
                  onClick={() => {
                    history.push(`/dynamic-form/design-form?formId=${item.id}`);
                  }}>
                  <Card
                    hoverable
                    className={styles.card}
                    actions={[
                      <a key="option1"
                         onClick={(e) => {
                           e.stopPropagation()
                           history.push(`/dynamic-form/design-form?formId=${item.id}`);
                         }}
                      ><TableOutlined /> 表格管理</a>,
                      <a key="option3"
                         onClick={(e) => {
                           e.stopPropagation()
                           history.push(`/product?formId=${item.id}&type=${item.type}`);
                         }}
                      ><EyeOutlined /> 查看数据</a>,
                      <a key="option2" style={{color: 'red'}} onClick={(e) => {
                        e.stopPropagation()
                        handleDel(item)
                      }}><DeleteOutlined /> 删除</a>,
                    ]}
                  >
                    <Card.Meta
                      // avatar={<img alt="" className={styles.cardAvatar} src={item.avatar} />}
                      title={item.name}
                      description={
                        <>
                          <Tooltip title={item.note}>
                            <Paragraph
                              italic
                              className={styles.item}
                              ellipsis={{
                                rows: 2,
                              }}
                              style={{height: 44}}
                            >
                              {item.note}
                            </Paragraph>
                          </Tooltip>
                          <div>更新时间: {dayjs(item.gmtModified).format("YYYY-MM-DD HH:mm:ss")}</div>
                        </>
                      }
                    />
                  </Card>
                </List.Item>
              );
            }
            return (
              <List.Item>
                <Button type="dashed" className={styles.newButton} onClick={() => {
                  history.push(`/dynamic-form/design-form`);
                }}>
                  <PlusOutlined/> 新增表格
                </Button>
              </List.Item>
            );
          }}
        />

        <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 40}}>
          <Pagination
            total={data?.total_records}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `总共 ${total} 条`}
            defaultPageSize={11}
            pageSize={pageInfo.size}
            current={pageInfo.page}
            pageSizeOptions={[11, 23, 35, 71]}
            onChange={(page, size) => {
              setPageInfo({
                page,
                size
              })
            }}
          />
        </div>
      </div>
    </PageContainer>
  );
};
export default CardList;
